<template>
    <div class="boxContentCss">
        <el-form ref="formRef" :model="form" label-position="right" label-width="auto">
            <EdCreateCard title="工单详情">
                <template #back>
                    <div class="createBack" @click="$utilsSet.goBack($router)" >
                        <svg-icon icon-class="back" /> 返回
                    </div>
                </template>
                <div class="zh_flex">
                    <div class="left">
                        <div class="left_top">
                                <el-row>
                                    <el-col :span="12"><span class="label_text">工单号：</span><span class="value_text">{{detailData.orderNo}}</span></el-col>
                                    <el-col :span="12"><span class="label_text">工单类型：</span><span class="value_text">{{returnName(detailData['orderType'], orderTypeParams.options)}}</span></el-col>
                                    <el-col :span="12">
                                        <span class="label_text">状态：</span>
                                        <!-- <el-button class="ed-table-bottom ed_8_border">{{detailData.status}}</el-button> -->
                                        <el-button class="ed-table-bottom ed_1_border" v-if="detailData.status == 'confirm'">待确认</el-button>
                                        <el-button class="ed-table-bottom ed_2_border" v-if="detailData.status == 'confirmed'">已确认</el-button>
                                        <el-button class="ed-table-bottom ed_3_border" v-if="detailData.status == 'reject'">已驳回</el-button>
                                        <el-button class="ed-table-bottom ed_4_border" v-if="detailData.status == 'pending'">待处理</el-button>
                                        <el-button class="ed-table-bottom ed_5_border" v-if="detailData.status == 'processing'">处理中</el-button>
                                        <el-button class="ed-table-bottom ed_7_border" v-if="detailData.status == 'success'">已完成</el-button>
                                        <el-button class="ed-table-bottom ed_8_border" v-if="detailData.status == 'paid'">已付款</el-button>
                                        <el-button class="ed-table-bottom ed_6_border" v-if="detailData.status == 'cancel'">已撤销</el-button>
                                        <el-button class="ed-table-bottom ed_9_border" v-if="detailData.status == 'close'">已关闭</el-button>
                                    </el-col>
                                    <el-col :span="12"><span class="label_text">优先级：</span><span class="value_text">
                                        <!-- {{detailData.level}} -->
                                            <div style="display: inline-block" v-if="detailData.level==0"><svg-icon icon-class="urgent0-svg"/><span class="radio_urgent radio_urgent_0">&nbsp;急</span></div>
                                            <div style="display: inline-block" v-if="detailData.level==1"><svg-icon icon-class="urgent1-svg"/><span class="radio_urgent radio_urgent_1">&nbsp;加急</span></div>
                                            <div style="display: inline-block" v-if="detailData.level==2"><svg-icon icon-class="urgent2-svg"/><span class="radio_urgent radio_urgent_2">&nbsp;紧急</span></div>
                                        </span></el-col>
                                    <el-col :span="12"><span class="label_text">工单地址：</span><span class="value_text">{{detailData.villageName}}{{detailData.address}}</span></el-col>
                                    <!-- <el-col :span="12"><span class="label_text">预约上门时间：</span><span class="value_text">{{detailData.appointmentTimeDesc}}</span></el-col> -->
                                    <!-- <el-col :span="12"><span class="label_text">预约上门时间：</span><span class="value_text">{{detailData.appointmentTime}}</span></el-col> -->
                                    <el-col :span="24"><span class="label_text">工单内容：</span><span class="value_text">{{detailData.serveDesc}}</span></el-col>
                                    <el-col :span="24">
                                        <div class="col_img">
                                            <!-- <img v-for="item in detailData.serveImages" :key="item" :src="item" alt=""> -->
                                             <el-image v-for="item in detailData.serveImages" :key="item" :src="item" :preview-src-list="[item]" fit="cover"></el-image>
                                        </div>
                                    </el-col>
                                    <el-col :span="12"><span class="label_text">报单人：</span><span class="value_text">{{detailData.openId ? detailData.proposer.substr(0,1)+'业主' : (detailData.proposer+'  '+detailData.proposerPhone) }} </span></el-col>
                                    <el-col :span="12"><span class="label_text">报单时间：</span><span class="value_text">{{detailData.createTime}}</span></el-col>
                                </el-row>
                        </div>
                        <el-button v-show="detailData.openId && detailData.status=='pending' || detailData.status=='processing'" class="ed-button ed_black-bottom chat_btn" @click="seeChat()" v-has="'property:workorder:seeChat'">查看聊天记录</el-button>
                        <!-- <div class="left_middle">
                            <el-row>
                                <el-col :span="24" v-if="detailData.repairer"><span class="label_text">接单人：</span><span class="value_text">{{detailData.repairer}}  {{detailData.repairerPhone}}</span></el-col>
                                <el-col :span="12" v-if="detailData.processTime"><span class="label_text">开始处理时间：</span><span class="value_text">{{detailData.processTime}}</span></el-col>
                                <el-col :span="12" v-if="detailData.finishTime"><span class="label_text">工单完成时间：</span><span class="value_text">{{detailData.finishTime}}</span></el-col>
                                <el-col :span="12" v-if="detailData.finishDesc"><span class="label_text">处理内容：</span><span class="value_text">{{detailData.finishDesc}}</span></el-col>
                                <el-col :span="24" v-if="detailData.finishImages">
                                    <span class="label_text">处理图片：</span>
                                    <span class="col_img">
                                        <img v-for="item in detailData.finishImages" :key="item" :src="item" alt="">
                                    </span>
                                </el-col>
                            </el-row>
                        </div>
                        <div class="left_bottom" v-if="detailData['status']=='paid'">
                            <el-row>
                                <el-col :span="24" v-if="detailData.fee"><span class="label_text">已付款：</span><span class="value_text money_text">￥{{detailData.fee}}</span></el-col>
                            </el-row>
                        </div>
                        <el-form-item class="form_btns">
                            <el-button v-if="detailData['status']=='confirmed'" class="ed-button ed_black-bottom" @click="assign()" v-has="'property:workorder:assign'">指派接单人</el-button>
                            <el-button v-if="detailData['status']=='reject'" class="ed-button ed_black-bottom" @click="edit()" v-has="'property:workorder:update'">编辑</el-button>
                        </el-form-item> -->
                    </div>
                    <div class="right">
                        <div class="right_title">处理过程跟踪</div>
                        <div>
                            <el-timeline :reverse="reverse">
                                <!-- <el-timeline-item
                                v-for="(activity, index) in activities"
                                :key="index"
                                :timestamp="activity.message"
                                color="#EED096"
                                size="large"
                                > -->
                                <el-timeline-item
                                v-for="(activity, index) in activities"
                                :key="index"
                                color="#EED096"
                                size="large"
                                >
                                    <div class="timeline_time">{{activity.createTime}}</div>
                                    <div class="timeline_content">{{activity.message}}</div>
                                    <div class="timeline_img">
                                        <el-image v-for="(item, index) in activity.images" :key="index"
                                                :src="item" :preview-src-list="[item]" fit="cover">
                                        </el-image>
                                    </div>
                                </el-timeline-item>
                            </el-timeline>
                        </div>
                    </div>
                </div>
            </EdCreateCard>
        </el-form>
        <AssignDialog ref="transferDialog" :isShow="changeDialog" @close-dialog="handleDialogClose" @save-dialog="handleDialogSave"></AssignDialog>
        <EdDialog :width="'645px'" :title="'查看聊天记录'" :showCloseBtn="false" :showSubmitBtnText="'关闭'" class="chatDialog" v-if="chatVisible"  @close-dialog="chatClose" @save-dialog="chatSave">
            <div class="workbench-center-box-msg" id="overflow">
                <div class="flex-box flex-center" style="margin-bottom: 17px" v-if="listItemMsg[0]">
                    <div class="fontSize12 line-height22 workbench-center-box-msg-time">{{listItemMsg[0].createTime}}</div>
                </div>
                <div v-for="itemMsg in listItemMsg" :key="itemMsg.id">
                    <div class="marginBottom18" v-if="itemMsg.isReply == 0">
                        <svg-icon class="fontSize40 middle" icon-class="work-oder-header-svg" />
                        <p v-if="itemMsg.msgType == 'text'" class="fontSize14 workbench-center-box-msg-other">{{JSON.parse(itemMsg.content).content}}</p>
                        <div v-if="itemMsg.msgType == 'voice'" class="fontSize14 workbench-center-box-msg-other" style="min-width: 80px" :style="{width:itemMsg.audioTimeLength * 2 + 80 + 'px' }">
                            <span v-if="voicePlayId != itemMsg.id" style="vertical-align: -5px" @click="audioClick(itemMsg)">
                                    <svg-icon icon-class="audio-svg" class="fontSize20"/>
                            </span>
                            <div class="bg voicePlay" v-if="voicePlayId == itemMsg.id" @click="stopAudio(itemMsg)"></div>
                            <span>{{itemMsg.audioTimeLength  + ' " '}}</span>
                        </div>
                        <video v-if="itemMsg.msgType == 'video'" preload="auto" controls
                                style="height: 200px;width: 300px;margin-left: 16px;display: inline-block;vertical-align: top"
                                :src="JSON.parse(itemMsg.content).content">
                        </video>
                        <el-image v-if="itemMsg.msgType == 'image'"
                                    :src="JSON.parse(itemMsg.content).content" :preview-src-list="[JSON.parse(itemMsg.content).content]" fit="cover">
                        </el-image>
                    </div>
                    <div class="flex-box flex-center" style="margin-bottom: 17px;margin-top: 33px" v-if="itemMsg.isTime">
                        <div class="fontSize12 line-height22 workbench-center-box-msg-time">{{itemMsg.createTime}}</div>
                    </div>
                    <div class="marginBottom18" style="text-align: right" v-if="itemMsg.isReply != 0">
                        <p class="fontSize14 workbench-center-box-msg-me">{{JSON.parse(itemMsg.content).content}}</p>
                        <svg-icon class="fontSize40 middle" icon-class="work-oder-header-two-svg" />
                    </div>
                </div>
            </div>
        </EdDialog>
    </div>
</template>

<script>
    import EdCreateCard from 'src/components/EdCreateCard.vue'
    import EdDateTimePicker from 'src/components/EdDateTimePicker.vue'
    import WisdomUploadSingle from "src/components/WisdomUploadSingle.vue";
    import EdSelect from 'src/components/EdSelect.vue'
    import EdDialog from 'src/components/EdDialog.vue';
    import AssignDialog from './AssignDialog.vue'
    import { defineComponent } from 'vue'
    import { orderTransfer, orderDetail, orderUpdate, } from "./api.js";
    import { getDictByCode } from "src/api/dictionaries";
    import { returnName } from "src/utils/common.js";
    import BenzAMRRecorder from 'benz-amr-recorder'
    import { msgWxListItem } from "src/api/workbench";
    export default defineComponent({
        name: "companyCreate",
        components: { EdCreateCard, EdDateTimePicker, WisdomUploadSingle, EdSelect, EdDialog, AssignDialog},
        data(){
            return{
                form: {},
                reverse: true,
                activities: [],
                changeDialog: false,
                detailData: {
                    orderNo: '',
                    orderType: '',
                    status: '',
                    level: '',
                    address: '',
                    appointmentTime: '',
                    serveDesc: '',
                    serveImages: [],
                    proposer: '',
                    proposerPhone: '',
                    repairer: '',
                    repairerPhone: '',
                    // 开始处理时间
                    finishTime: '',
                    finishImages: [],

                    // 明细
                    records: [],
                },
                orderTypeParams: {
                    options: []
                },
                // 查看聊天 dialog
                chatVisible: false,
                voicePlayId:null,
                listItemMsg: []
            }
        },
        activated(){
            // 获取 工单类型(物业人员-所属职能)
            getDictByCode('member_functions_type').then(res=>{
                this.orderTypeParams.options = res.data.items;
            })
            if(this.$route.query.id){
                // 编辑 
                this.isUpdate = true;
                this.orderDetail();
            }else {
              
            }
        },
        // mounted(){
        //     if(this.$route.query.id){
        //         // 编辑 
        //         this.isUpdate = true;
        //         this.orderDetail();
        //     }else {
              
        //     }
        // },
        methods:{
            orderDetail(){
                orderDetail({id:this.$route.query.id}).then(response => {
                    if(response.code == 20000) {
                        this.detailData = response.data;

                        // 处理追踪数据
                        response.data.records&&response.data.records.forEach((v, i)=>{
                            v['images'] = v['images']&&JSON.parse(v['images']);
                        })
                        this.activities = response.data.records;
                    }
                })
            },
            // 编辑（已驳回）
            edit(){
                this.$router.push({
                    path: '/property/workorder-add',
                    query: { id: this.$route.query.id }
                })
            },
            // 指派给（已确认）
            assign(){
                this.changeDialog = true;
            },
            handleDialogClose(){
                this.changeDialog = false;
            },
            handleDialogSave(data){
                // console.log('radio---->', data)
                let params = {
                    orderId: this.$route.query.id,
                    repairerId: data['id'],
                    repairer: data['name'],
                    repairerPhone: data['mobile'],
                };
                orderTransfer(params).then((res)=>{
                    if(res.code == 20000) {
                        this.$message.success({
                            message: '操作成功！',
                            duration: 2000,
                            center:true
                        });
                        this.changeDialog = false;
                        this.orderDetail();
                    }
                }).catch(()=>{
                    this.$refs.transferDialog.cancelStatus()
                })
            },
            onSubmit(formName){
                this.$refs[formName].validate((valid) => {
                    if(valid){
                        let query = this.form.copy();
                        if(this.isUpdate){
                            companyUpdate(query).then(response => {
                                if(response.code == 20000) {
                                    this.disabled = false;
                                    this.$message.success({
                                        message: '保存成功',
                                        center: true,
                                        duration: 2000,
                                    });
                                    // this.form.id = response.data;
                                    if(this.$route.query.type !=0){
                                        window.setTimeout(() => {
                                            this.$utilsSet.goBack(this.$router);
                                        }, 600)
                                    }
                                }else {
                                    this.disabled = false
                                }
                            }).catch(()=>{
                                this.disabled = false
                            })
                        }else{
                            companyAdd(query).then(response => {
                                if(response.code == 20000) {
                                    this.disabled = false;
                                    this.$message.success({
                                        message: '添加成功',
                                        center: true,
                                        duration: 2000,
                                    });
                                    // this.form.id = response.data;
                                    if(this.$route.query.type !=0){
                                        window.setTimeout(() => {
                                            this.$utilsSet.goBack(this.$router);
                                        }, 600)
                                    }
                                }else {
                                    this.disabled = false
                                }
                            }).catch(()=>{
                                this.disabled = false
                            })
                        }
                    }
                })
            },
            returnName(val, options){
                return returnName(val, options)
            },
            // 查看聊天记录
            seeChat(){
                this.getChatList();
                this.chatVisible = true;
            },
            // 查看聊天 提交
            chatSave(){
                this.chatVisible = false;
            },
            // 查看聊天 关闭
            chatClose(){
                this.chatVisible = false;
            },
            audioClick(item){
                console.log('item--->', item)
                let amr = new BenzAMRRecorder();
                this.voicePlayId = item.id;
                let _this = this;
                amr.initWithUrl(JSON.parse(item.content).content).then(function() {
                    // amr.isPlaying() 返回音频的播放状态 是否正在播放 返回boolean类型
                    if(amr.isPlaying()){
                        amr.stop();
                    } else {
                        amr.play();
                        _this.voicePlay = false;
                    }
                });

                amr.onEnded(function() {
                    _this.voicePlayId = null;
                    console.log('播放结束');
                });
            },
            stopAudio(item){
                let amr = new BenzAMRRecorder();
                amr.stop();
                this.voicePlayId = null;
            },
            getChatList(){
                let query = new Object();
                query.appId = this.detailData.appId;
                query.openId = this.detailData.openId;
                msgWxListItem(query).then(response=>{
                    if(response.code == 20000) {
                        let _this = this;
                        // this.listItemMsg = this.listItemMsg.concat(response.data);
                        this.listItemMsg = response.data;

                        this.$nextTick(()=>{
                            let message = document.getElementById('overflow');
                            message.scrollTop = message.scrollHeight;
                        });
                        let amr = new BenzAMRRecorder();
                        for (let i=0;i<response.data.length;i++){
                            _this.$set(response.data[i],"audioTimeLength",0)
                            // 设置语音时长
                            if(response.data[i].msgType == "voice"){
                                amr.initWithUrl(JSON.parse(response.data[i].content).content).then(function() {
                                    _this.$set(response.data[i],"audioTimeLength",Math.ceil(amr.getDuration()))
                                });
                            }
                        }

                        // 显示超过30分钟的时间
                        for (let i=0;i<this.listItemMsg.length-1;i++){
                            if(this.daysDistance(this.listItemMsg[i++].createTime,this.listItemMsg[i].createTime) >= 30){
                                this.listItemMsg[i].isTime = true;
                            }
                        }
                    }
                })
            },
            daysDistance(time1, time2) {
                //判断开始时间是否大于结束日期
                //截取字符串，得到日期部分"2009-12-02",用split把字符串分隔成数组
                let begin1=time1.substr(0,10).split("-");
                let end1=time2.substr(0,10).split("-");
                //将拆分的数组重新组合，并实例成化新的日期对象
                let date1=new Date(begin1[1] + - + begin1[2] + - + begin1[0]);
                let date2=new Date(end1[1] + - + end1[2] + - + end1[0]);
                //得到两个日期之间的差值m，以分钟为单位
                //Math.abs(date2-date1)计算出以毫秒为单位的差值
                //Math.abs(date2-date1)/1000得到以秒为单位的差值
                //Math.abs(date2-date1)/1000/60得到以分钟为单位的差值
                let m=parseInt(Math.abs(date2-date1)/1000/60);
                //小时数和分钟数相加得到总的分钟数
                //time1.substr(11,2)截取字符串得到时间的小时数
                //parseInt(time1.substr(11,2))*60把小时数转化成为分钟
                let min1=parseInt(time1.substr(11,2))*60+parseInt(time1.substr(14,2));
                let min2=parseInt(time2.substr(11,2))*60+parseInt(time2.substr(14,2));
                //两个分钟数相减得到时间部分的差值，以分钟为单位
                let n=min2-min1;
                //将日期和时间两个部分计算出来的差值相加，即得到两个时间相减后的分钟数
                return m+n;
            },
        }
    })
</script>

<style scoped lang="scss">
    :deep .el-form-item{
        .el-form-item__content{
            .el-input{
                 input{
                    width: 230px !important;
                }
            }
        }
    }
    .form_btns{
        display: flex;
        justify-content: flex-end;
        margin-right: 10px;
        margin-top: 18px;
    }
    :deep .zh_flex{
        padding: 16px !important;
        font-family: 'Noto Sans SC';
        font-style: normal;
        font-weight: 400;
        font-size: 14px;
        // line-height: 22px;
        line-height: 28px;
        .left{
            flex: 3;
            border-right: 1px solid #e5e7eb;
            // border: 1px solid #e5e7eb;
            padding: 0 40px 5px 20px;
            .left_top{
                border-bottom: 1px solid #e5e7eb;
                padding: 7px 0 18px;
                padding-top: 0;
                .col_img{
                    margin-left: 65px;   
                    img{
                        display: inline-block;
                        width: 120px;
                        height: 120px;
                        margin-right: 10px;
                    }
                } 
            }
            .left_middle{
                border-bottom: 1px solid #e5e7eb;
                padding: 7px 0 18px;
                .col_img{
                    vertical-align: text-top;
                    img{
                        display: inline-block;
                        width: 120px;
                        height: 120px;
                        margin-right: 10px;
                    }
                } 
            }
            .left_bottom{
                border-bottom: 1px solid #e5e7eb;
                padding: 7px 0 0;
                border-bottom: none;
                .money_text{
                    font-weight: 500;
                    font-size: 16px;
                    line-height: 22px;
                    color: #414448;
                }
            }
            .label_text{
                color: #606266;
            }
            .value_text{
                color: #414448;
            }
            .el-col{
                padding: 5px 0;
            }
        } 
        .right{
            flex: 1;
            padding: 5px 20px;
            // border: 1px solid #e5e7eb;
            .right_title{
                color: #303133;
                font-weight: 500;
                font-size: 16px;
                line-height: 24px;
                margin-bottom: 20px;
            }
            .el-timeline-item__content{
                font-weight: 400;
                font-size: 12px;
                line-height: 18px;
                color: #606266;
            }
            .el-timeline-item__timestamp{
                color: #414448;
                font-weight: 500;
                font-size: 14px;
                line-height: 24px;
            }
            .timeline_time{
                font-weight: 400;
                font-size: 12px;
                line-height: 18px;
                color: #606266;
            }
            .timeline_content{
                font-weight: 500;
                font-size: 14px;
                line-height: 24px;
                color: #414448;
                margin: 5px 0;
            }
            .timeline_img{
                img{
                    width: 72px;
                    height: 72px;
                    margin-right: 5px;
                    cursor: pointer;
                }
            }
        }
    }
    .radio_urgent_0{
        color: #EED096;
    }
    .radio_urgent_1{
        color: #F3B385;
    }
    .radio_urgent_2{
        color: #EE7171;
    }
    .chat_btn{
        margin-top: 20px;
    }
    :deep .workbench-center-box-msg{
        padding: 20px;
        overflow-y: auto;
        // height: calc(100% - 168px);
        height: 100%;
        background: #FBFBFB;
        &::-webkit-scrollbar-thumb{
            background-color: #C1C1C1;
            border-radius: 2px;
        }
        .workbench-center-box-msg-time{
            background: #DFDFDF;border-radius: 4px;color: #ffffff;padding: 2px 8px;text-align: center;
        }
        .workbench-center-box-msg-other{
            background: #3B3D41;border-radius: 2px 8px 8px 8px;line-height: 22px;padding: 8px 16px;display: inline-block;max-width: 60%;margin-left: 16px;color: #ffffff
        }
        .workbench-center-box-msg-me{
            background: #EED096;border-radius: 8px 2px 8px 8px;line-height: 38px;min-height: 38px;padding: 0 16px;display: inline-block;max-width: 60%;margin-left: 16px;color: #ffffff;
            vertical-align: middle;
        }
        .el-image{
            display: inline-block;
            vertical-align: top;
            width: 102px;height: 84px;border-radius: 2px 8px 8px 8px;
            margin-left: 16px;
        }
    }
    :deep .chatDialog{
        .el-dialog__body{
            height: 470px;
            padding: 0 10px;
            border-top: 1px solid #DEE0E7;
            border-bottom: 1px solid #DEE0E7;
        }
    }
</style>